package com.stb.isharemessage.ui.feed;

import java.util.ArrayList;



import java.util.HashMap;
//import java.util.Iterator;
//import java.util.Map;
//import java.util.Set;
import java.util.Date;



import java.util.List;

import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.util.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

























import com.nostra13.universalimageloader.core.ImageLoader;
import com.speed.im.login.EncryptionUtil;
import com.spice.im.BaseActivity;
import com.spice.im.ContactFrameActivity;
import com.spice.im.FlippingLoadingDialog;
import com.spice.im.R;
import com.spice.im.SimpleListDialog;
import com.spice.im.SimpleListDialog.onSimpleListItemClickListener;
import com.spice.im.SimpleListDialogAdapter;
import com.spice.im.SpiceApplication;
import com.spice.im.preference.PreferenceActivity;
import com.spice.im.preference.PreferenceActivity.exPhoneCallListener;
import com.spice.im.ui.HandyTextView;
import com.spice.im.utils.Feed;
import com.spice.im.utils.FeedComment;
import com.spice.im.utils.HeaderLayout;
import com.spice.im.utils.HeaderLayout.HeaderStyle;
import com.spice.im.utils.HeaderLayout.onMiddleImageButtonClickListener;
import com.spice.im.utils.HeaderLayout.onRightImageButtonClickListener;
import com.spice.im.utils.ImageFetcher;
import com.spiceim.db.TContactGroupAdapter;
//import com.stb.isharemessage.R;
import com.stb.isharemessage.service.aidl.IXmppFacade;
//import com.dodola.model.DuitangInfo;
//import com.dodowaterfall.widget.FlowView;
//import com.example.android.bitmapfun.util.AsyncTask;
//import com.example.android.bitmapfun.util.ImageFetcher;
import com.sdp.custom.CImageMarkView;
import com.sdp.custom.ImagePoint;
import com.stb.isharemessage.BeemApplication;
import com.stb.isharemessage.BeemService;
import com.stb.isharemessage.IConnectionStatusCallback;
//import com.stb.isharemessage.service.DynamicsItemParcelable;
//import com.stb.isharemessage.service.MyHashMap;
//import com.stb.isharemessage.service.UserInfo;
import com.stb.isharemessage.service.XmppConnectionAdapter;
//import com.stb.isharemessage.ui.AddDynamicsActivity;
//import com.stb.isharemessage.ui.ContactFrameActivity;
//import com.stb.isharemessage.ui.HandyTextView;
//import com.stb.isharemessage.ui.feed.OtherFeedListAdapter.ViewHolder;
import com.stb.isharemessage.ui.feed.OtherFeedListPopupWindow.onOtherFeedListPopupItemClickListner;
//import com.stb.isharemessage.ui.profile.OtherProfileActivity;
//import com.stb.isharemessage.ui.register.BaseActivity;
//import com.stb.isharemessage.ui.register.FlippingLoadingDialog;
//import com.stb.isharemessage.ui.register.SimpleListDialog;
//import com.stb.isharemessage.ui.register.SimpleListDialogAdapter;
//import com.stb.isharemessage.ui.register.SimpleListDialog.onSimpleListItemClickListener;
import com.stb.isharemessage.utils.BeemBroadcastReceiver;
import com.stb.isharemessage.utils.BeemConnectivity;
//import com.stb.isharemessage.utils.DateUtils;
//import com.stb.isharemessage.utils.Feed;
//import com.stb.isharemessage.utils.FeedComment;
//import com.stb.isharemessage.utils.HeaderLayout;
//import com.stb.isharemessage.utils.JsonResolveUtils;
//import com.stb.isharemessage.utils.HeaderLayout.HeaderStyle;
//import com.stb.isharemessage.utils.HeaderLayout.onMiddleImageButtonClickListener;
//import com.stb.isharemessage.utils.HeaderLayout.onRightImageButtonClickListener;

//import com.beem.push.utils.AsyncTask;























import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
//import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.ClipboardManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;


@SuppressWarnings("deprecation")
public class FeedProfileActivity extends BaseActivity implements
		OnItemClickListener, onRightImageButtonClickListener,
		onOtherFeedListPopupItemClickListner, OnClickListener, IConnectionStatusCallback,OnTouchListener {
    private static final Intent SERVICE_INTENT = new Intent();

    static {
    	SERVICE_INTENT.setComponent(new ComponentName("com.spice.im", "com.stb.isharemessage.BeemService"));//自身应用pkg名称，非service所在pkg名称
    }
	private HeaderLayout mHeaderLayout;
	private ListView mLvList;
	private EmoticonsTextView mEtvEditerTitle;
//	private HandyTextView mEtvEditerTitle;
	private ImageView mIvEmote;
	private Button mBtnSend;
	private EmoticonsEditText mEetEditer;

	private View mHeaderView;
	private ImageView mIvAvatar;
//	private FlowView mIvAvatar;
	private TextView mTvTime;
	private HandyTextView mEtvName;

//	private ImageView mIvVip;
//	private ImageView mIvGroupRole;
//	private ImageView mIvIndustry;
//	private ImageView mIvWeibo;
//	private ImageView mIvTxWeibo;
//	private ImageView mIvRenRen;
//	private ImageView mIvDevice;
//	private ImageView mIvRelation;
//	private ImageView mIvMultipic;
	private EmoticonsTextView mEtvContent;
//	private HandyTextView mEtvContent;
	private CImageMarkView mIvContent;
	private ImageView contentImage_cover;
	private LinearLayout mLayoutComment;
	private TextView mTvCommentCount;
	private TextView mTvDistance;
	private RelativeLayout mLayoutLoading;
	private TextView mTvLoading;
	private ImageView mIvLoading;
	private EmoteInputView mInputView;

	private FeedProfileCommentsAdapter mAdapter;

//	private NearByPeopleProfile mProfile;
//	private NearByPeople mPeople;
	private Feed mFeed;
//	private String mOtherusername;
	private OtherFeedListPopupWindow mPopupWindow;
	private int mWidthAndHeight;
	private int mHeaderHeight;
	private SimpleListDialog mDialog;
	private Animation mLoadingAnimation;

	private List<FeedComment> mComments = new ArrayList<FeedComment>();
	private List<FeedComment> mComments_temp = new ArrayList<FeedComment>();
	public void clearComments(){
    	mComments.clear();
    }
    public void addItem(List<FeedComment> datas) {
    	if(datas!=null){
//    		mComments.clear();
        	for (FeedComment info : datas) {
        		mComments.add(info);
            }
    	}
    }
	private ImageFetcher mImageFetcher;
	private int itemWidth;
	private int column_count = 3;// 显示列数 just for image cut
	
	private Context mContext;
    //网络状态start
	private View mNetErrorView;
	private TextView mConnect_status_info;
	private ImageView mConnect_status_btn;
    private exPhoneCallListener myPhoneCallListener = null;
    private TelephonyManager tm = null;
    //网络状态end
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		mContext = this;
		setContentView(R.layout.activity_feedprofile);
		DisplayMetrics metric = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metric);
		mScreenWidth = metric.widthPixels - 12;
		mScreenHeight = metric.heightPixels;
		tContactGroupAdapter = TContactGroupAdapter.getInstance(this);
        mImageFetcher = new ImageFetcher(this, mScreenWidth);
        mImageFetcher.setUListype(1);
        mImageFetcher.setLoadingImage(R.drawable.empty_photo);
        mImageFetcher.setExitTasksEarly(false);
        mLoadingDialog = new FlippingLoadingDialog(this, "请求提交中");
//        this.registerReceiver(mReceiver, new IntentFilter(BeemBroadcastReceiver.BEEM_CONNECTION_CLOSED));//原来的网络状态注释掉
        itemWidth = this.getWindowManager().getDefaultDisplay().getWidth() / column_count;// 根据屏幕大小计算每列宽度
		initViews();
		initEvents();
		init();
        //网络状态start
        mNetErrorView = findViewById(R.id.net_status_bar_top);
        mConnect_status_info = (TextView)mNetErrorView.findViewById(R.id.net_status_bar_info_top2);
        mConnect_status_btn = (ImageView)mNetErrorView.findViewById(R.id.net_status_bar_btn);
        mConnect_status_btn.setOnClickListener(this);
        
	    IntentFilter mFilter = new IntentFilter();
	    mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); // 添加接收网络连接状态改变的Action
	    registerReceiver(mNetWorkReceiver, mFilter);
        /* 添加自己实现的PhoneStateListener */
        myPhoneCallListener = new exPhoneCallListener();
       
       /* 取得电话服务 */
        tm =(TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
       
        /* 注册电话通信Listener */
        tm.listen(myPhoneCallListener,PhoneStateListener.LISTEN_CALL_STATE);
	    //网络状态end
        SpiceApplication.getInstance().addActivity(this);
	}

	@Override
	public void onBackPressed() {
		if (mInputView.isShown()) {
			mInputView.setVisibility(View.GONE);
		} else {
			finish();
		}
	}

	@Override
	protected void initViews() {
		mHeaderLayout = (HeaderLayout) findViewById(R.id.feedprofile_header);
		mLvList = (ListView) findViewById(R.id.feedprofile_lv_list);
		mEtvEditerTitle = (EmoticonsTextView) findViewById(R.id.feedprofile_etv_editertitle);
		mIvEmote = (ImageView) findViewById(R.id.feedprofile_iv_emote);
		mBtnSend = (Button) findViewById(R.id.feedprofile_btn_send);
		mEetEditer = (EmoticonsEditText) findViewById(R.id.feedprofile_eet_editer);
		mInputView = (EmoteInputView) findViewById(R.id.feedprofile_eiv_input);

//		mHeaderView = LayoutInflater.from(FeedProfileActivity.this).inflate(
//				R.layout.header_feed, null);
		mHeaderView = LayoutInflater.from(FeedProfileActivity.this).inflate(
				R.layout.listitem_feedhead, null);
		mIvAvatar = (ImageView) mHeaderView
				.findViewById(R.id.feed_item_iv_avatar);
//		mIvAvatar = (FlowView) mHeaderView
//		.findViewById(R.id.header_feed_iv_avatar);
		mTvTime = (TextView) mHeaderView.findViewById(R.id.feed_item_htv_time);
		mEtvName = (HandyTextView) mHeaderView
				.findViewById(R.id.feed_item_htv_name);
		
		mEtvContent = (EmoticonsTextView) mHeaderView
				.findViewById(R.id.feed_item_etv_content);
//		mIvContent = (ImageView) mHeaderView
//				.findViewById(R.id.header_feed_iv_content);
//		View mFeedFanerBlocks = mHeaderView.findViewById(R.id.feed_faner_block0);
		mIvContent = (CImageMarkView) mHeaderView
				.findViewById(R.id.feed_item_iv_content);
		contentImage_cover = (ImageView) mHeaderView
		.findViewById(R.id.feed_item_iv_content_cover);
		
		mLayoutComment = (LinearLayout) mHeaderView
				.findViewById(R.id.header_feed_layout_comment);
		mTvCommentCount = (TextView) mHeaderView
				.findViewById(R.id.header_feed_tv_commentcount);
		mTvDistance = (TextView) mHeaderView
				.findViewById(R.id.header_feed_tv_distance);
		mLayoutLoading = (RelativeLayout) mHeaderView
				.findViewById(R.id.header_feed_layout_loading);
		mTvLoading = (TextView) mHeaderView
				.findViewById(R.id.header_feed_tv_loading);
		mIvLoading = (ImageView) mHeaderView
				.findViewById(R.id.header_feed_iv_loading);
	}

	@Override
	protected void initEvents() {
		mLvList.setOnItemClickListener(this);
		mLayoutComment.setOnClickListener(this);
		mEetEditer.setOnTouchListener(this);
		mBtnSend.setOnClickListener(this);
		mIvEmote.setOnClickListener(this);
	}

	private void init() {
//		mProfile = getIntent().getParcelableExtra("entity_profile");
//		mPeople = getIntent().getParcelableExtra("entity_people");
		mFeed = getIntent().getParcelableExtra("entity_feed");
//		mOtherusername = getIntent().getParcelableExtra("otherusername");
//		if(mOtherusername!=null){
//			int atIndex = mOtherusername.lastIndexOf("@");
//    		if(atIndex<0)
//    			;
//    		else
//    			mOtherusername = StringUtils.parseName(mOtherusername);
//		}
		
//		mHeaderLayout.init(HeaderStyle.TITLE_RIGHT_IMAGEBUTTON);
////		mHeaderLayout.setTitleRightImageButton(mFeed.getUser_id()+"的动态留言内容", null,
////				R.drawable.ic_topbar_more, this);
//		mHeaderLayout.setTitleRightImageButton(mFeed.getNickname()+"的动态留言", null,
//				R.drawable.ic_topbar_more, this);
		
		mHeaderLayout.init(HeaderStyle.TITLE_CHAT);
		mHeaderLayout.setTitleChat(R.drawable.ic_chat_dis_1,
				R.drawable.bg_chat_dis_active, mFeed.getNickname()+"的动态留言",
				"",
				R.drawable.ic_topbar_more,//ic_menu_invite  ic_topbar_profile
				new OnMiddleImageButtonClickListener(),
				R.drawable.return2,
				new OnRightImageButtonClickListener());
		
		initPopupWindow();
		initHeaderView();
		mInputView.setEditText(mEetEditer);
		mLvList.addHeaderView(mHeaderView);
		mAdapter = new FeedProfileCommentsAdapter(
				FeedProfileActivity.this, mComments);
		mLvList.setAdapter(mAdapter);
//		mAdapter.notifyDataSetChanged();//20141216 added by allen
		getComments();
	}

	private void initPopupWindow() {
		mWidthAndHeight = (int) TypedValue.applyDimension(
				TypedValue.COMPLEX_UNIT_DIP, 120, getResources()
						.getDisplayMetrics());
		mHeaderHeight = (int) TypedValue.applyDimension(
				TypedValue.COMPLEX_UNIT_DIP, 48, getResources()
						.getDisplayMetrics());
		mPopupWindow = new OtherFeedListPopupWindow(this, mWidthAndHeight,
				mWidthAndHeight);
		mPopupWindow.setOnOtherFeedListPopupItemClickListner(this);
	}
	private String[] imgArray = null;
	private String[] fanerArray = null;
	private String img = null;
	private String faner = null;
	private ArrayList<ImagePoint> pointList = null;
	private String fanerTemp = null;
	private JSONArray array = null;
	private ImagePoint imagePoint = null;
	private JSONObject object = null;
	private String markTempId = null;
	private String x = null;
	private String y = null;
	private String markStr = null; 
	
	private TContactGroupAdapter tContactGroupAdapter = null;
	String headpath = "";
	
	private void initHeaderView() {
//		mIvAvatar.setItemWidth(itemWidth);
//		mIvAvatar.set_url(mFeed.getUser_id());//contact.getJIDWithRes()
//		mIvAvatar.set_roomname("");
//		mIvAvatar.setName(mFeed.getNickname());
//		mIvAvatar.setMActivity(this);
		
		if(tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mFeed.getUser_id()+"@0"))!=null)
			headpath = tContactGroupAdapter.getTContactGroup(StringUtils.parseBareAddress(mFeed.getUser_id()+"@0")).getAvatarPath();	
		
		
//		mIvAvatar.setHeadimg(XmppConnectionAdapter.downloadPrefix.replace("/javacenterhome/","/")+headpath);
		mImageFetcher.loadNormalImage(XmppConnectionAdapter.downloadPrefix.replace("/javacenterhome/","/")+headpath, mIvAvatar,1,36,36,null);
		mEtvName.setText(mFeed.getNickname());
		
		mTvTime.setText(mFeed.getTime());
//		mLayoutGender.setBackgroundResource(R.drawable.bg_gender_famal);
//		mIvGender.setImageResource(R.drawable.ic_user_famale);
//		mHtvAge.setText("28");
//		if (mPeople.getIsVip() != 0) {
//			mIvVip.setVisibility(View.VISIBLE);
//		} else {
//			mIvVip.setVisibility(View.GONE);
//		}
//		if (mPeople.getIsGroupRole() != 0) {
//			mIvGroupRole.setVisibility(View.VISIBLE);
//			if (mPeople.getIsGroupRole() == 1) {
//				mIvGroupRole
//						.setImageResource(R.drawable.ic_userinfo_groupowner);
//			}
//		} else {
//			mIvIndustry.setVisibility(View.GONE);
//		}
//		if (!android.text.TextUtils.isEmpty(mPeople.getIndustry())) {
//			mIvIndustry.setVisibility(View.VISIBLE);
//			mIvIndustry.setImageBitmap(PhotoUtils.getIndustry(
//					FeedProfileActivity.this, mPeople.getIndustry()));
//		} else {
//			mIvIndustry.setVisibility(View.GONE);
//		}
//		if (mPeople.getIsbindWeibo() != 0) {
//			mIvWeibo.setVisibility(View.VISIBLE);
//			if (mPeople.getIsbindWeibo() == 1) {
//				mIvWeibo.setImageResource(R.drawable.ic_userinfo_weibov);
//			}
//		} else {
//			mIvWeibo.setVisibility(View.GONE);
//		}
//		if (mPeople.getIsbindTxWeibo() != 0) {
//			mIvTxWeibo.setVisibility(View.VISIBLE);
//			if (mPeople.getIsbindTxWeibo() == 1) {
//				mIvTxWeibo.setImageResource(R.drawable.ic_userinfo_tweibov);
//			}
//		} else {
//			mIvTxWeibo.setVisibility(View.GONE);
//		}
//
//		if (mPeople.getIsbindRenRen() != 0) {
//			mIvRenRen.setVisibility(View.VISIBLE);
//		} else {
//			mIvRenRen.setVisibility(View.GONE);
//		}
//		if (mPeople.getDevice() != 0) {
//			mIvDevice.setVisibility(View.VISIBLE);
//			if (mPeople.getDevice() == 1) {
//				mIvDevice.setImageResource(R.drawable.ic_userinfo_android);
//			}
//			if (mPeople.getDevice() == 2) {
//				mIvDevice.setImageResource(R.drawable.ic_userinfo_apple);
//			}
//		} else {
//			mIvDevice.setVisibility(View.GONE);
//		}
//		if (mPeople.getIsRelation() != 0) {
//			mIvRelation.setVisibility(View.VISIBLE);
//		} else {
//			mIvRelation.setVisibility(View.GONE);
//		}
//		if (mPeople.getIsMultipic() != 0) {
//			mIvMultipic.setVisibility(View.VISIBLE);
//		} else {
//			mIvMultipic.setVisibility(View.GONE);
//		}
		mEtvContent.setText(mFeed.getContent());
		if (mFeed.getContentImage() == null) {
			mIvContent.setVisibility(View.GONE);
		} else {
			mIvContent.setVisibility(View.VISIBLE);
//			mIvContent.setImageResource(R.drawable.space_both);
			imgArray = null;
			fanerArray = null;
			img = mFeed.getContentImage();
			if(img!=null 
					&& !img.equalsIgnoreCase("null")
					&& img.length()!=0){
				imgArray = img.split("\\|");
			}
			faner = mFeed.getFaner();
			if(faner!=null 
					&& !faner.equalsIgnoreCase("null")
					&& faner.length()!=0){
				fanerArray = faner.split("\\|");
			}
			if(imgArray!=null){
				switch(imgArray.length){
					case 0:
						break;
					case 1:
						get(contentImage_cover,mIvContent,0);
						break;
					case 2:
						break;
					case 3:
						break;
					case 4:
						break;
					default:
						break;
				}
			}
			
		}
		mTvDistance.setText(mFeed.getSite());
		mTvCommentCount.setText(mFeed.getCommentCount() + "");
	}
	public void get(ImageView contentImage_cover,CImageMarkView mIvContent,int m){
		if(m==0){
//			if(mType==1)
//				;
//			else
			//mOtherusername
			ImageLoader.getInstance().displayImage(XmppConnectionAdapter.downloadPrefix.replace("/javacenterhome/","/")+"/thinkis/userfiles/"+mFeed.getUser_id()+"/images/photo/"+imgArray[m], contentImage_cover,SpiceApplication.getInstance().options);
//			mImageFetcher.loadNormalImage(XmppConnectionAdapter.downloadPrefix+mFeed.getUser_id()+"/"+imgArray[m], contentImage_cover,mScreenWidth,0,0,null);//背景图
		}else if(m==1){
//			mImageFetcher.loadNormalImage(XmppConnectionAdapter.downloadPrefix+mFeed.getUser_id()+"/"+imgArray[m], contentImage_cover,mScreenWidth,0,0,null);//背景图
			ImageLoader.getInstance().displayImage(XmppConnectionAdapter.downloadPrefix.replace("/javacenterhome/","/")+"/thinkis/userfiles/"+mFeed.getUser_id()+"/images/photo/"+imgArray[m], contentImage_cover,SpiceApplication.getInstance().options);
		}else if(m==2){
//			mImageFetcher.loadNormalImage(XmppConnectionAdapter.downloadPrefix+mFeed.getUser_id()+"/"+imgArray[m], contentImage_cover,mScreenWidth,0,0,null);//背景图
			ImageLoader.getInstance().displayImage(XmppConnectionAdapter.downloadPrefix.replace("/javacenterhome/","/")+"/thinkis/userfiles/"+mFeed.getUser_id()+"/images/photo/"+imgArray[m], contentImage_cover,SpiceApplication.getInstance().options);
		}else if(m==3){
//			mImageFetcher.loadNormalImage(XmppConnectionAdapter.downloadPrefix+mFeed.getUser_id()+"/"+imgArray[m], contentImage_cover,mScreenWidth,0,0,null);//背景图
			ImageLoader.getInstance().displayImage(XmppConnectionAdapter.downloadPrefix.replace("/javacenterhome/","/")+"/thinkis/userfiles/"+mFeed.getUser_id()+"/images/photo/"+imgArray[m], contentImage_cover,SpiceApplication.getInstance().options);
		}
		pointList = new ArrayList<ImagePoint>();
		if(fanerArray!=null && fanerArray.length>=m){
			for(int n=0;n<fanerArray.length;n++){
				if(fanerArray[n].startsWith(imgArray[m])){
					fanerTemp = fanerArray[n].substring(imgArray[m].length()+1, fanerArray[n].length());
					if(fanerTemp!=null
							&& !fanerTemp.equalsIgnoreCase("null")
							&& fanerTemp.length()!=0)
					try {
						array = new JSONArray(fanerTemp);
						imagePoint = null;
						for (int i = 0; i < array.length(); i++) {
							object = array.getJSONObject(i);
							markTempId = object.getString("markTempId");
							x = object.getString("x");
							y = object.getString("y");
							markStr = object.getString("markStr");
							imagePoint = new ImagePoint(Integer.parseInt(markTempId),
							Float.valueOf(x).floatValue(),
							Float.valueOf(y).floatValue(),
							markStr);
							pointList.add(imagePoint);
						}
					} catch (JSONException e) {
						e.printStackTrace();
					} catch(Exception e){
						e.printStackTrace();
					}
					break;
				}
			}
		}
		if(m==0)
			mIvContent.init(this, null,false,pointList);
		else if(m==1)
			mIvContent.init(this, null,false,pointList);
		else if(m==2)
			mIvContent.init(this, null,false,pointList);
		else if(m==3)
			mIvContent.init(this, null,false,pointList);
	}
	@Override
	public void onClick() {

		mPopupWindow.showAtLocation(mHeaderLayout, Gravity.RIGHT | Gravity.TOP,
				-10, mHeaderHeight + 10);
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		if (arg3 != -1) {
			FeedComment comment = mComments.get((int) arg3);
			String[] codes = new String[] { "回复", "复制文本", "举报" };
			mDialog = new SimpleListDialog(this);
			mDialog.setTitle("提示");
			mDialog.setTitleLineVisibility(View.GONE);
			mDialog.setAdapter(new SimpleListDialogAdapter(this, codes));
			mDialog.setOnSimpleListItemClickListener(new OnReplyDialogItemClickListener(
					comment));
			mDialog.show();
		}
	}

	@Override
	public void onCopy(View v) {
		String text = mFeed.getContent();
		copy(text);
	}

	@Override
	public void onReport(View v) {
		report();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		//网络设置
        case R.id.net_status_bar_btn:
			setNetworkMethod(this);
		break;
		case R.id.header_feed_layout_comment:
			mEtvEditerTitle.setText(null);
			mEtvEditerTitle.setVisibility(View.GONE);
			mEetEditer.requestFocus();
			showKeyBoard();
			break;

		case R.id.feedprofile_iv_emote:
			mEetEditer.requestFocus();
			if (mInputView.isShown()) {
				showKeyBoard();
			} else {
				hideKeyBoard();
				mInputView.setVisibility(View.VISIBLE);
			}
			break;
		case R.id.feedprofile_btn_send:
			String content = mEetEditer.getText().toString().trim();
			if (TextUtils.isEmpty(content)) {
				showCustomToast("请输入评论内容");
				mEetEditer.requestFocus();
			} else {
				String reply = null;
				if (mEtvEditerTitle.isShown()) {
					reply = mEtvEditerTitle.getText().toString().trim();
				}
				content = TextUtils.isEmpty(reply) ? content : reply + content;
//				FeedComment comment = new FeedComment("测试用户",
//						"nearby_people_other", content, DateUtils.formatDate(
//								FeedProfileActivity.this,
//								System.currentTimeMillis()));
//				mComments.add(0, comment);
//				mAdapter.notifyDataSetChanged();
				
				initialAddDynamics(mFeed.getDynamicid(),content);//20141215
			}
//			mEtvEditerTitle.setText(null);
//			mEtvEditerTitle.setVisibility(View.GONE);
//			mEetEditer.setText(null);
//			mInputView.setVisibility(View.GONE);
//			hideKeyBoard();
			break;
		}
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {

		if (v.getId() == R.id.feedprofile_eet_editer) {
			showKeyBoard();
		}
		return false;
	}

	private void copy(String text) {
		ClipboardManager m = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
		m.setText(text);
		showCustomToast("已成功复制文本");
		mEetEditer.requestFocus();
	}

	private void report() {
		String[] codes = getResources()
				.getStringArray(R.array.reportfeed_items);
		mDialog = new SimpleListDialog(this);
		mDialog.setTitle("举报留言");
		mDialog.setTitleLineVisibility(View.GONE);
		mDialog.setAdapter(new SimpleListDialogAdapter(this, codes));
		mDialog.setOnSimpleListItemClickListener(new OnReportDialogItemClickListener());
		mDialog.show();
	}

	private class OnReportDialogItemClickListener implements
			onSimpleListItemClickListener {

		@Override
		public void onItemClick(int position) {
			showLoadingDialog("正在提交,请稍后...");
			new Handler().postDelayed(new Runnable() {

				@Override
				public void run() {
					dismissLoadingDialog();
					showCustomToast("举报的信息已提交");
				}
			}, 1500);
		}
	}

	private class OnReplyDialogItemClickListener implements
			onSimpleListItemClickListener {

		private FeedComment mComment;

		public OnReplyDialogItemClickListener(FeedComment comment) {
			mComment = comment;
		}

		@Override
		public void onItemClick(int position) {
			switch (position) {
			case 0:
				mEtvEditerTitle.setVisibility(View.VISIBLE);
				mEtvEditerTitle.setText("回复" + mComment.getName() + " :");
				mEetEditer.requestFocus();
				showKeyBoard();
				break;

			case 1:
				String text = mComment.getContent();
				copy(text);
				break;

			case 2:
				report();
				break;
			}
		}

	}

	private void startLoading() {
		if (!mLayoutLoading.isShown()) {
			mLayoutLoading.setVisibility(View.VISIBLE);
		}
		if (mIvLoading != null) {
			mIvLoading.setVisibility(View.VISIBLE);
			mTvLoading.setText("评论加载中");
			mLoadingAnimation = AnimationUtils.loadAnimation(
					FeedProfileActivity.this, R.anim.loading);
			mIvLoading.startAnimation(mLoadingAnimation);
		}
	}

	private void refreshCommentTitle() {
		if (mComments != null) {
			if (mComments.size() > 0 && !mAdapter.isEmpty()) {
				mLayoutLoading.setVisibility(View.GONE);
			} else {
				mIvLoading.clearAnimation();
				mIvLoading.setVisibility(View.GONE);
				mTvLoading.setText("暂无评论");
				mLayoutLoading.setVisibility(View.VISIBLE);
			}
		}
	}

	private void showKeyBoard() {
		if (mInputView.isShown()) {
			mInputView.setVisibility(View.GONE);
		}
		((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
				.showSoftInput(mEetEditer, 0);
	}

	private void hideKeyBoard() {
		((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
				.hideSoftInputFromWindow(FeedProfileActivity.this
						.getCurrentFocus().getWindowToken(),
						InputMethodManager.HIDE_NOT_ALWAYS);
	}

	private void getComments() {
		putAsyncTask(new com.spice.im.utils.AsyncTask<Void, Void, Boolean>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				startLoading();
			}

			@Override
			protected Boolean doInBackground(Void... params) {
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
//				return JsonResolveUtils.resoleFeedComment(
//						FeedProfileActivity.this, mComments);
				getDynamicsComments(mFeed.getUser_id(),mFeed.getDynamicid());
				if(errorType == 5)
					return true;
				else
					return false;
			}

			@Override
			protected void onPostExecute(Boolean result) {
				super.onPostExecute(result);
//				mIvAvatar.set_url(mFeed.getUser_id()+domainresource);//contact.getJIDWithRes()
				mLayoutLoading.setVisibility(View.GONE);
				mIvLoading.clearAnimation();
				if (!result) {
					if(errorType == 0)
						showCustomToast("暂无评论...");
					else
						showCustomToast("评论数据加载失败...");
//					mLayoutLoading.setVisibility(View.GONE);
//					mIvLoading.clearAnimation();
				} else {
					
					addItem(mComments_temp);
					mAdapter.notifyDataSetChanged();
					refreshCommentTitle();
				}
			}

		});
	}
	
    @Override
    protected void onResume() {
		super.onResume();
		if (!mBinded){
			mBinded = bindService(new Intent(this, BeemService.class), mServConn, BIND_AUTO_CREATE);
		}
    }
    @Override
    protected void onPause() {
		super.onPause();
    }
    @Override
    protected void onDestroy() {
    	//销毁contentImage_cover
    	if(contentImage_cover!=null){
    		Drawable drawable = contentImage_cover.getDrawable();
    		if(drawable!=null){
    			if (drawable instanceof BitmapDrawable){
			        Bitmap bmp =  ((BitmapDrawable) drawable).getBitmap();
			    	if (null != bmp && !bmp.isRecycled()){
			    		bmp.recycle();
			    		bmp = null;
			    	}
			    	contentImage_cover.setImageBitmap(null);
    			}
    		}
    	}
    	//销毁mIvAvatar
    	if(mIvAvatar!=null){
    		Drawable drawable = mIvAvatar.getDrawable();
    		if(drawable!=null){
    			if (drawable instanceof BitmapDrawable){
			        Bitmap bmp =  ((BitmapDrawable) drawable).getBitmap();
			    	if (null != bmp && !bmp.isRecycled()){
			    		bmp.recycle();
			    		bmp = null;
			    	}
			    	mIvAvatar.setImageBitmap(null);
    			}
    		}
    	}
	    try{//网络状态相关
		    if(mXmppFacade!=null && mXmppFacade.getXmppConnectionAdapter()!=null)
		    	mXmppFacade.getXmppConnectionAdapter().unRegisterConnectionStatusCallback();
	    }catch (RemoteException e) {
	    	e.printStackTrace();
	    }
		if (mBinded) {
			unbindService(mServConn);
			mBinded = false;
		}
		//网络状态start
		unregisterReceiver(mNetWorkReceiver); // 删除广播
		if(tm!=null){
			tm.listen(myPhoneCallListener,PhoneStateListener.LISTEN_NONE);//取消监听即可
			tm = null;
		}
		if(myPhoneCallListener!=null)
			myPhoneCallListener = null;
		//网络状态end
//		this.unregisterReceiver(mReceiver);//原来的网络状态注释掉
		super.onDestroy();
    }
	
	private IXmppFacade mXmppFacade;
	private boolean mBinded = false;
	private final ServiceConnection mServConn = new BeemServiceConnection(this);
//	private final BeemBroadcastReceiver mReceiver = new BeemBroadcastReceiver();//原来的网络状态注释掉
	private String domainresource = "";
    private class BeemServiceConnection implements ServiceConnection {
    	private Context mContext;
		/**
		 * constructor.
		 */
		public BeemServiceConnection(Context context) {
			mContext = context;
		}
	
		/**
		 * {@inheritDoc}
		 */
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
		    mXmppFacade = IXmppFacade.Stub.asInterface(service);
		    if(mXmppFacade!=null){
		    	mBinded = true;//20130804 added by allen
		    	try{
		    		mXmppFacade.getXmppConnectionAdapter().registerConnectionStatusCallback(FeedProfileActivity.this);//网络状态相关
		    	}catch(Exception e){}
//		    	try{
//		    		mXmppFacade.getXmppConnectionAdapter().getUserInfo().getJid();
//		    	}catch(Exception e){
//		    		e.printStackTrace();
//		    	}
		    }
		}
	
		/**
		 * {@inheritDoc}
		 */
		@Override
		public void onServiceDisconnected(ComponentName name) {
			 try{//网络状态相关
				    if(mXmppFacade!=null && mXmppFacade.getXmppConnectionAdapter()!=null)
				    	mXmppFacade.getXmppConnectionAdapter().unRegisterConnectionStatusCallback();
			    }catch (RemoteException e) {
			    	e.printStackTrace();
			    }
			mBinded = false;
		    mXmppFacade = null;
		}
    }
	protected FlippingLoadingDialog mLoadingDialog;
	private Handler mHandler = new Handler() {
		
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 0:
				showLoadingDialog("请稍后,正在设置...0%");
				break;
			case 1:
				showLoadingDialog("请稍后,正在设置..."+msg.arg1+"%");
				break;
			case 2:
//				pictures.add(picturename); 
//				faners.put(picturename, fanermark); 
				dismissLoadingDialog();
				break;
			case 3:
//				bulidCurrentAvator();
				break;
			case 4:
//				pictures.clear();
//				faners.clear();
				dismissLoadingDialog();
				if(errorType == 5)
					showCustomToast("提交成功!");
				else
					showCustomToast(errorMsg[errorType]);
				addItem(mComments_temp);
				mAdapter.notifyDataSetChanged();
				mEtvEditerTitle.setText(null);
				mEtvEditerTitle.setVisibility(View.GONE);
				mEetEditer.setText(null);
				mInputView.setVisibility(View.GONE);
				hideKeyBoard();
				
//				Intent intent = new Intent(AddDynamicsActivity.this,
//						OtherFeedListActivity.class);
////				intent.putExtra("entity_profile", mProfile);
////				intent.putExtra("entity_people", mPeople);
//				if(roomid!=null
//						&& !roomid.equalsIgnoreCase("null")
//						&& roomid.length()!=0)
//					intent.putExtra("otherusername", roomid);	
//				else
//				intent.putExtra("otherusername", ui.getJid());//StringUtils.parseName(ui.getJid())
//				intent.putExtra("myjid", ui.getJid());
//				intent.putExtra("mFrom", "1");
//				intent.putExtra("mtype", mtype);
//				startActivity(intent);
//				AddDynamicsActivity.this.finish();
				break;
			default:
				break;
			}
		}
	};
	
	protected void showLoadingDialog(String text) {
		if (text != null) {
			mLoadingDialog.setText(text);
		}
		mLoadingDialog.show();
	}

	protected void dismissLoadingDialog() {
		if (mLoadingDialog.isShowing()) {
			mLoadingDialog.dismiss();
		}
	}
	private void initialAddDynamics(final String originalid,final String memo) {

		putAsyncTask(new com.spice.im.utils.AsyncTask<Void, Void, Boolean>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				showLoadingDialog("正在加载,请稍后...");
			}

			@Override
			protected Boolean doInBackground(Void... params) {
				try{
//					initCurrentAvatar(context);
//					StringBuffer str_pictures = new StringBuffer();
//					StringBuffer str_faner = new StringBuffer();
//					for(int i=0;i<pictures.size();i++){
//						str_pictures.append(pictures.get(i)+"|");
//					}
//				    Iterator iter = faners.entrySet().iterator();
//					while (iter.hasNext()) {
//						Map.Entry entry = (Map.Entry) iter.next();
//						Object key = entry.getKey();
//						Object val = entry.getValue();
//						str_faner.append(key+"="+val+"|");
//					}
					
//					AddDynamics(memo,str_pictures.toString(),str_faner.toString());
					AddDynamics2(originalid,memo,"","");
				}catch(Exception e){
					return false;
				}
				return true;
			}

			@Override
			protected void onPostExecute(Boolean result) {
				super.onPostExecute(result);
				dismissLoadingDialog();
				if (!result) {
					showCustomToast("数据加载失败...");
				} else {
					mHandler.sendEmptyMessage(4);
				}
			}

		});
	} 
    
//	private String roomid = null;
//	private MyHashMap myHashMap = null;
	private HashMap hashMap = null;
//	private List<DynamicsItemParcelable> results = null;
//	private DynamicsItemParcelable dynamicsItemParcelable = null;
	private List<DynamicsCommentsItem> results = null;
	private DynamicsCommentsItem dynamicsItem = null;
	private int CTTotal = 0;//总条数
	private int totalnumber = 0;//本次查询返回条数
	
    private int currentPage = 0;
    private int numberresult = 50;
    private int pageCount = 0;//总页数
    private FeedComment comment = null;
    
//	public void AddDynamics(String originalid,String memo,String str_pictures,String str_faner){
//		mComments_temp.clear();
//		if(BeemConnectivity.isConnected(getApplicationContext())){
//		    try {
//		    	if(mXmppFacade!=null){
//			    	if (mXmppFacade.getXmppConnectionAdapter()!=null 
//							&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null
//							&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected() 
//			    			&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
//			    			&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAlive()){
//			    		
//			    		String mtype = "0";
//			    		String dynamicid = "";
//			    		String username = StringUtils.parseName(mXmppFacade.getXmppConnectionAdapter().getJID());//个人动态
////			    		if(roomid!=null
////			    				&& !roomid.equalsIgnoreCase("null")
////			    				&& roomid.length()!=0)
////			    			username = roomid;//群动态
//			    		String otherusername = "";
//			    		String longitude = String.valueOf(SpiceApplication.getInstance().mLongitude);
//			    		String latitude = String.valueOf(SpiceApplication.getInstance().mLatitude);
////			    		String memo;
////			    		String str_pictures;
////			    		String str_faner;
//			    		String time = com.spice.im.utils.TextUtils.dateToMillis(new Date());
//			    		String geolocation = SpiceApplication.getInstance().mGpsAddr;
//			    		int startIndex = 0;
//			    		int numResults = 100;
////			    		mXmppFacade.getDynamicsItems(mtype,
////			    	    		dynamicid,
////			    	    		username,
////			    	    		otherusername,
////			    	    		longitude,
////			    	    		latitude,
////			    	    		memo,
////			    	    		str_pictures,
////			    	    		str_faner,
////			    	    		time,
////			    	    		geolocation,
////			    	    		startIndex,
////			    	    		numResults);
//			    		myHashMap = mXmppFacade.getDynamicsCommentsItems(mtype, 
//			    				dynamicid, 
//			    				originalid, 
//			    				username, 
//			    				otherusername, 
//			    				longitude, 
//			    				latitude, 
//			    				memo, 
//			    				str_pictures, 
//			    				str_faner, 
//			    				time, 
//			    				geolocation, 
//			    				startIndex, 
//			    				numResults);
//			    		
//			    		if(myHashMap!=null)
//				    		hashMap = myHashMap.getMap();
//				    		if(hashMap!=null){
//				    		Set set = hashMap.entrySet() ;
//				    		java.util.Iterator it = hashMap.entrySet().iterator();
//				    		while(it.hasNext()){
//					    		java.util.Map.Entry entry = (java.util.Map.Entry)it.next();
//					    		CTTotal = Integer.parseInt((String)entry.getKey());// 返回与此项对应的键
//					    		results = (List<DynamicsItemParcelable>)entry.getValue(); //返回与此项对应的值
//					    		
//					    		pageCount = CTTotal%numberresult==0? CTTotal/numberresult-1 : CTTotal/numberresult;
//		                        //System.out.println(entry.getValue());
//				    		} 
//				    		totalnumber = myHashMap.getTotalnumber();
//				    		Log.e("MMMMMMMMMMMM20140828OtherFeedListActivityMMMMMMMMMMMM", "++++++++++++++CTTotal="+CTTotal);
//				    		Log.e("MMMMMMMMMMMM20140828OtherFeedListActivityMMMMMMMMMMMM", "++++++++++++++totalnumber="+totalnumber);
//				    		}
//				    		if(results!=null && results.size()!=0){
//				    			errorType = 5;
//				    			comment = new FeedComment(username,
//				    					mXmppFacade.getXmppConnectionAdapter().getUserInfo().getAvatarId(), memo, time);
////			    				mComments.add(0, comment);
//				    			mComments_temp.add(0, comment);
//				    			for(int i=0;i<results.size();i++){
//				    				dynamicsItemParcelable = (DynamicsItemParcelable)results.get(i);
////				    				feed = new Feed(dynamicsItemParcelable.getId()+"","",dynamicsItemParcelable.getTime(), 
////				    						dynamicsItemParcelable.getMemo(), 
////				    						dynamicsItemParcelable.getPictures(),
////				    						dynamicsItemParcelable.getFaner(), 
////				    						dynamicsItemParcelable.getDistance(),
////											3,//commentCount
////											dynamicsItemParcelable.getEmail(),
////											dynamicsItemParcelable.getName(),
////											dynamicsItemParcelable.getUid());
////				    				
////				    				mFeeds.add(feed);
//				    				
////				    				comment = new FeedComment(dynamicsItemParcelable.getName(),
////				    						dynamicsItemParcelable.getEmail(), dynamicsItemParcelable.getMemo(), dynamicsItemParcelable.getTime());
////				    				mComments.add(0, comment);
//				    			}
//				    		}else{
//				    			if(results!=null && results.size()==0)
//				    				errorType = 0;
//				    			else
//				    				errorType = 6;
//				    		}
//			    	}else
//			    		errorType = 1;
//		    	}else
//		    		errorType = 2;
//		    }catch (RemoteException e) {
//		    	errorType = 3;
//		    	e.printStackTrace();
//		    	
//		    } catch (Exception e){
//		    	errorType = 3;
//		    	e.printStackTrace();
//		    }
//		}else{
//	    	errorType = 4;
//	    }
//	}
	
	
    private boolean AddDynamics2(String originalid,String memo,String str_pictures,String str_faner){//page=1 keystr=""
    	mComments_temp.clear();
//    	showCustomToast("initGeGroupMembers1");
    	Log.e("================GroupDetailsActivity.java ================", "++++++++++++++initGeGroupMembers1111++++++++++++++");
		try{
			if(BeemConnectivity.isConnected(getApplicationContext())){
				Log.e("================GroupDetailsActivity.java ================", "++++++++++++++initGeGroupMembers2222++++++++++++++");
		    if(mXmppFacade!=null 
					&& mXmppFacade.getXmppConnectionAdapter()!=null 
					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null//&& !mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
//					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected()
//					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
//					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAlive()
					){
		    		Log.e("================GroupDetailsActivity.java ================", "++++++++++++++initGeGroupMembers3333++++++++++++++");
		    		String mtype = "0";
		    		String dynamicid = "";
		    		String username = StringUtils.parseName(mXmppFacade.getXmppConnectionAdapter().getJID());//个人动态
//		    		if(roomid!=null
//		    				&& !roomid.equalsIgnoreCase("null")
//		    				&& roomid.length()!=0)
//		    			username = roomid;//群动态
		    		String otherusername = "";
		    		String longitude = String.valueOf(SpiceApplication.getInstance().mLongitude);
		    		String latitude = String.valueOf(SpiceApplication.getInstance().mLatitude);
//		    		String memo;
//		    		String str_pictures;
//		    		String str_faner;
		    		String time = com.spice.im.utils.TextUtils.dateToMillis(new Date());
		    		String geolocation = SpiceApplication.getInstance().mGpsAddr;
		    		int startIndex = 0;
		    		int numResults = 100;
		    		
		    		DynamicsCommentsIQ reqXML = new DynamicsCommentsIQ();
		            reqXML.setId("1234567890");
		            reqXML.setApikey("abcdefghijklmnopqrstuvwxyz");
		            reqXML.setMtype(mtype);
		            reqXML.setDynamicid(dynamicid);
		            reqXML.setOriginalid(originalid);
		            reqXML.setUsername(StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID()));//2
		            reqXML.setOtherusername(otherusername);
		            reqXML.setLongitude(longitude);
		            reqXML.setLatitude(latitude);
		            reqXML.setMemo(memo);
		            reqXML.setPictures(str_pictures);
		            reqXML.setFaner(str_faner);
		            reqXML.setTime(time);
		            reqXML.setGeolocation(geolocation);
		            reqXML.setRadius(5000*1000+"");
		            reqXML.setStartIndex(currentPage*numberresult+"");
		            reqXML.setNumResults(numberresult+"");
		            
		            
		            
		            SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
//		    	    String username = settings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, "");
		            String login = settings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, "");
		            String uuid = mXmppFacade.getXmppConnectionAdapter().getAdaptee().getUUID(this,login);
//		            reqXML.setUuid(uuid);
	//	            String hashcode = "";//apikey+username(uid)+time 使用登录成功后返回的sessionid作为密码做3des运算
		            String hash_dest_src = "abcdefghijklmnopqrstuvwxyz"+ StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID())+time;
		            String hash_dest = EncryptionUtil.getHash2(hash_dest_src, "SHA");
		            reqXML.setHashcode(hash_dest);
		            reqXML.setType(IQ.Type.SET);
		            String elementName = "dynamicscommentsiq"; 
		    		String namespace = "com:stb:dynamicscommentsiq";
		    		DynamicsCommentsIQResponseProvider provider = new DynamicsCommentsIQResponseProvider();
		            Packet rt =  mXmppFacade.getXmppConnectionAdapter().excute(reqXML, "dynamicscommentsiq", "com:stb:dynamicscommentsiq", provider);
		            
		            if(rt!=null){
		                if (rt instanceof DynamicsCommentsIQResponse) {
		                	final DynamicsCommentsIQResponse dynamicsCommentsIQResponse = (DynamicsCommentsIQResponse) rt;
	
		                    if (dynamicsCommentsIQResponse.getChildElementXML().contains(
		                            "com:stb:dynamicscommentsiq")) {
	//	    					MainActivity.this.runOnUiThread(new Runnable() {
	//		                    	
	//    							@Override
	//    							public void run() {
	//    								showCustomToast("服务器应答消息："+contactGroupListIQResponse.toXML().toString());
	//    							}
	//    						});
		                        String Id = dynamicsCommentsIQResponse.getId();
		                        String Apikey = dynamicsCommentsIQResponse.getApikey();
		                        try{
		                        	CTTotal = Integer.parseInt(dynamicsCommentsIQResponse.getCttotal());
		                        	totalnumber = Integer.parseInt(dynamicsCommentsIQResponse.getTotalnumber());
		                        	pageCount = CTTotal%numberresult==0? CTTotal/numberresult-1 : CTTotal/numberresult;
		                        }catch(Exception e){
		                        	CTTotal = 0;
		                        	totalnumber = 0;
		                        }
		                        results = dynamicsCommentsIQResponse.getDynamics();
					    		if(results!=null && results.size()!=0){
					    			errorType = 5;
					    			comment = new FeedComment(username,
					    					mXmppFacade.getXmppConnectionAdapter().getAvatarpath(), memo, time);
//				    				mComments.add(0, comment);
					    			mComments_temp.add(0, comment);
					    			for(int i=0;i<results.size();i++){
					    				dynamicsItem = (DynamicsCommentsItem)results.get(i);
					    			}
					    			return true;
					    		}else{
					    			if(results!=null && results.size()==0)
					    				errorType = 0;
					    			else
					    				errorType = 6;
					    		}
//		                        String retcode = dynamicsIQResponse.getRetcode();
//		                        memo = dynamicsIQResponse.getMemo();
//		                        if(retcode.equalsIgnoreCase("0000")){
//		                        	errorType = 0;
//		                        	return true;
//		                        }
//		                        else if(retcode.equalsIgnoreCase("0002"))
//		                        	errorType = 6;
//		                        else
//		                        	errorType = 5;
		                        
		                    }
		                } 
		            }
		    		errorType = 1;

		    }else
		    	errorType = 1;
		    
			}else
				errorType = 4;
		}catch(RemoteException e){
			e.printStackTrace();
			errorType = 2;
		}catch(Exception e){
			e.printStackTrace();
			errorType = 3;
		}
		return false;
    }
	
	
	private String[] errorMsg = new String[]{"没有相关记录.",
			"服务连接中1-1,请稍候再试.",
			"服务连接中1-2,请稍候再试.",
			"服务连接中1-3,请稍候再试.",
			"网络连接不可用,请检查你的网络设置.",
			"",
			"请求异常,稍候重试!"};
	private int errorType = 5;	

	public void getDynamicsComments(String otherusername,String originalid){
		mComments_temp.clear();
		if(BeemConnectivity.isConnected(getApplicationContext())){
		    try {
		    	if(mXmppFacade!=null){
			    	if (mXmppFacade.getXmppConnectionAdapter()!=null 
							&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null
							&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected() 
			    			&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
			    			&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAlive()){
			    		domainresource = "@"
			    			+StringUtils.parseServer(mXmppFacade.getXmppConnectionAdapter().getJID())
			    			+"/"
			    			+StringUtils.parseResource(mXmppFacade.getXmppConnectionAdapter().getJID());
			    		if(mFeed.getUser_id().length()==11)
			    			;
			    		else
			    			domainresource = "@conference."
			    				+StringUtils.parseServer(mXmppFacade.getXmppConnectionAdapter().getJID());
			    		String mtype = "2";
			    		String dynamicid = "";
			    		String username = StringUtils.parseName(mXmppFacade.getXmppConnectionAdapter().getJID());//个人动态
//			    		if(roomid!=null
//			    				&& !roomid.equalsIgnoreCase("null")
//			    				&& roomid.length()!=0)
//			    			username = roomid;//群动态
//			    		String otherusername = "";
			    		String longitude = String.valueOf(SpiceApplication.getInstance().mLongitude);
			    		String latitude = String.valueOf(SpiceApplication.getInstance().mLatitude);
//			    		String memo;
//			    		String str_pictures;
//			    		String str_faner;
			    		String time = com.spice.im.utils.TextUtils.dateToMillis(new Date());
			    		String geolocation = SpiceApplication.getInstance().mGpsAddr;
			    		int startIndex = 0;
			    		int numResults = 100;
//			    		mXmppFacade.getDynamicsItems(mtype,
//			    	    		dynamicid,
//			    	    		username,
//			    	    		otherusername,
//			    	    		longitude,
//			    	    		latitude,
//			    	    		memo,
//			    	    		str_pictures,
//			    	    		str_faner,
//			    	    		time,
//			    	    		geolocation,
//			    	    		startIndex,
//			    	    		numResults);
//			    		myHashMap = mXmppFacade.getDynamicsCommentsItems(mtype, 
//			    				dynamicid, 
//			    				originalid, 
//			    				username, 
//			    				otherusername, 
//			    				longitude, 
//			    				latitude, 
//			    				"", 
//			    				"", 
//			    				"", 
//			    				time, 
//			    				geolocation, 
//			    				startIndex, 
//			    				numResults);
//			    		
//			    		if(myHashMap!=null)
//				    		hashMap = myHashMap.getMap();
//				    		if(hashMap!=null){
//				    		Set set = hashMap.entrySet() ;
//				    		java.util.Iterator it = hashMap.entrySet().iterator();
//				    		while(it.hasNext()){
//					    		java.util.Map.Entry entry = (java.util.Map.Entry)it.next();
//					    		CTTotal = Integer.parseInt((String)entry.getKey());// 返回与此项对应的键
//					    		results = (List<DynamicsItemParcelable>)entry.getValue(); //返回与此项对应的值
//					    		
//					    		pageCount = CTTotal%numberresult==0? CTTotal/numberresult-1 : CTTotal/numberresult;
//		                        //System.out.println(entry.getValue());
//				    		} 
//				    		totalnumber = myHashMap.getTotalnumber();
//				    		Log.e("MMMMMMMMMMMM20140828OtherFeedListActivityMMMMMMMMMMMM", "++++++++++++++CTTotal="+CTTotal);
//				    		Log.e("MMMMMMMMMMMM20140828OtherFeedListActivityMMMMMMMMMMMM", "++++++++++++++totalnumber="+totalnumber);
//				    		}
//				    		if(results!=null && results.size()!=0){
//				    			errorType = 5;
//				    			for(int i=0;i<results.size();i++){
//				    				dynamicsItemParcelable = (DynamicsItemParcelable)results.get(i);
////				    				feed = new Feed(dynamicsItemParcelable.getId()+"","",dynamicsItemParcelable.getTime(), 
////				    						dynamicsItemParcelable.getMemo(), 
////				    						dynamicsItemParcelable.getPictures(),
////				    						dynamicsItemParcelable.getFaner(), 
////				    						dynamicsItemParcelable.getDistance(),
////											3,//commentCount
////											dynamicsItemParcelable.getEmail(),
////											dynamicsItemParcelable.getName(),
////											dynamicsItemParcelable.getUid());
////				    				
////				    				mFeeds.add(feed);
//				    				
//				    				comment = new FeedComment(dynamicsItemParcelable.getName(),
//				    						dynamicsItemParcelable.getEmail(), dynamicsItemParcelable.getMemo(), dynamicsItemParcelable.getTime());
////				    				mComments.add(0, comment);
//				    				mComments_temp.add(0, comment);
//				    			}
//				    		}else{
//				    			if(results!=null && results.size()==0)
//				    				errorType = 0;
//				    			else
//				    				errorType = 6;
//				    		}
			    		
			    		DynamicsCommentsIQ reqXML = new DynamicsCommentsIQ();
			            reqXML.setId("1234567890");
			            reqXML.setApikey("abcdefghijklmnopqrstuvwxyz");
			            reqXML.setMtype(mtype);
			            reqXML.setDynamicid(dynamicid);
			            reqXML.setOriginalid(originalid);
			            reqXML.setUsername(StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID()));//2
			            reqXML.setOtherusername(otherusername);
			            reqXML.setLongitude(longitude);
			            reqXML.setLatitude(latitude);
			            reqXML.setMemo("");
			            reqXML.setPictures("");
			            reqXML.setFaner("");
			            reqXML.setTime(time);
			            reqXML.setGeolocation(geolocation);
			            reqXML.setRadius(5000*1000+"");
			            reqXML.setStartIndex(currentPage*numberresult+"");
			            reqXML.setNumResults(numberresult+"");
			            
			            
			            
			            SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
//			    	    String username = settings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, "");
			            String login = settings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, "");
			            String uuid = mXmppFacade.getXmppConnectionAdapter().getAdaptee().getUUID(this,login);
//			            reqXML.setUuid(uuid);
		//	            String hashcode = "";//apikey+username(uid)+time 使用登录成功后返回的sessionid作为密码做3des运算
			            String hash_dest_src = "abcdefghijklmnopqrstuvwxyz"+ StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID())+time;
			            String hash_dest = EncryptionUtil.getHash2(hash_dest_src, "SHA");
			            reqXML.setHashcode(hash_dest);
			            reqXML.setType(IQ.Type.SET);
			            String elementName = "dynamicscommentsiq"; 
			    		String namespace = "com:stb:dynamicscommentsiq";
			    		DynamicsCommentsIQResponseProvider provider = new DynamicsCommentsIQResponseProvider();
			            Packet rt =  mXmppFacade.getXmppConnectionAdapter().excute(reqXML, "dynamicscommentsiq", "com:stb:dynamicscommentsiq", provider);
			            
			            if(rt!=null){
			                if (rt instanceof DynamicsCommentsIQResponse) {
			                	final DynamicsCommentsIQResponse dynamicsCommentsIQResponse = (DynamicsCommentsIQResponse) rt;
		
			                    if (dynamicsCommentsIQResponse.getChildElementXML().contains(
			                            "com:stb:dynamicscommentsiq")) {
		//	    					MainActivity.this.runOnUiThread(new Runnable() {
		//		                    	
		//    							@Override
		//    							public void run() {
		//    								showCustomToast("服务器应答消息："+contactGroupListIQResponse.toXML().toString());
		//    							}
		//    						});
			                        String Id = dynamicsCommentsIQResponse.getId();
			                        String Apikey = dynamicsCommentsIQResponse.getApikey();
			                        try{
			                        	CTTotal = Integer.parseInt(dynamicsCommentsIQResponse.getCttotal());
			                        	totalnumber = Integer.parseInt(dynamicsCommentsIQResponse.getTotalnumber());
			                        	pageCount = CTTotal%numberresult==0? CTTotal/numberresult-1 : CTTotal/numberresult;
			                        }catch(Exception e){
			                        	CTTotal = 0;
			                        	totalnumber = 0;
			                        }
			                        results = dynamicsCommentsIQResponse.getDynamics();
						    		if(results!=null && results.size()!=0){
						    			errorType = 5;
//						    			comment = new FeedComment(username,
//						    					mXmppFacade.getXmppConnectionAdapter().getAvatarpath(), memo, time);
////					    				mComments.add(0, comment);
//						    			mComments_temp.add(0, comment);
						    			for(int i=0;i<results.size();i++){
						    				dynamicsItem = (DynamicsCommentsItem)results.get(i);
						    				comment = new FeedComment(dynamicsItem.getName(),
						    						dynamicsItem.getUser_id(), dynamicsItem.getMemo(), dynamicsItem.getTime());
//						    				dynamicsItem.getUser_id();
//				    						mComments.add(0, comment);
						    				mComments_temp.add(0, comment);
						    			}
//						    			return true;
						    		}else{
						    			if(results!=null && results.size()==0)
						    				errorType = 0;
						    			else
						    				errorType = 6;
						    		}
//			                        String retcode = dynamicsIQResponse.getRetcode();
//			                        memo = dynamicsIQResponse.getMemo();
//			                        if(retcode.equalsIgnoreCase("0000")){
//			                        	errorType = 0;
//			                        	return true;
//			                        }
//			                        else if(retcode.equalsIgnoreCase("0002"))
//			                        	errorType = 6;
//			                        else
//			                        	errorType = 5;
			                        
			                    }
			                } 
			            }
			    	}else
			    		errorType = 1;
		    	}else
		    		errorType = 2;
		    }catch (RemoteException e) {
		    	errorType = 3;
		    	e.printStackTrace();
		    	
		    } catch (Exception e){
		    	errorType = 3;
		    	e.printStackTrace();
		    }
		}else{
	    	errorType = 4;
	    }
	}
	
	protected class OnRightImageButtonClickListener implements
	onRightImageButtonClickListener {

		@Override
		public void onClick() {
	//		mChatPopupWindow.showAtLocation(mHeaderLayout, Gravity.RIGHT
	//				| Gravity.TOP, -10, mHeaderHeight + 10);
			
			Intent intent = new Intent(FeedProfileActivity.this, ContactFrameActivity.class);//GroupProfileActivity.class multiuserlistmain.class
	    	startActivity(intent);
	    	FeedProfileActivity.this.finish();
	    	
		}
	}
	protected class OnMiddleImageButtonClickListener implements
	onMiddleImageButtonClickListener {

		@Override
		public void onClick() {
			mPopupWindow.showAtLocation(mHeaderLayout, Gravity.RIGHT | Gravity.TOP,
					-10, mHeaderHeight + 10);
		}
	}
	
	//网络状态 start
		@Override
		public void connectionStatusChanged(int connectedState, String reason) {
			Log.e("MMMMM20140604MMMMMMMMMMMM", "++++++++++++++connectionStatusChanged0++++++++++++");
			switch (connectedState) {
			case 0://connectionClosed
				mHandler3.sendEmptyMessage(0);
				break;
			case 1://connectionClosedOnError
//				mConnectErrorView.setVisibility(View.VISIBLE);
//				mNetErrorView.setVisibility(View.VISIBLE);
//				mConnect_status_info.setText("连接异常!");
				mHandler3.sendEmptyMessage(1);
				break;
			case 2://reconnectingIn
//				mNetErrorView.setVisibility(View.VISIBLE);
//				mConnect_status_info.setText("连接中...");
				mHandler3.sendEmptyMessage(2);
				break;
			case 3://reconnectionFailed
//				mNetErrorView.setVisibility(View.VISIBLE);
//				mConnect_status_info.setText("重连失败!");
				mHandler3.sendEmptyMessage(3);
				break;
			case 4://reconnectionSuccessful
//				mNetErrorView.setVisibility(View.GONE);
				mHandler3.sendEmptyMessage(4);

			default:
				break;
			}
		}
		Handler mHandler3 = new Handler() {

			@Override
			public void handleMessage(android.os.Message msg) {
				super.handleMessage(msg);
				switch (msg.what) {
				case 0:
					break;

				case 1:
					mNetErrorView.setVisibility(View.VISIBLE);
					if(BeemConnectivity.isConnected(mContext))
					mConnect_status_info.setText("连接异常!");
					break;

				case 2:
					mNetErrorView.setVisibility(View.VISIBLE);
					if(BeemConnectivity.isConnected(mContext))
					mConnect_status_info.setText("连接中...");
					break;
				case 3:
					mNetErrorView.setVisibility(View.VISIBLE);
					if(BeemConnectivity.isConnected(mContext))
					mConnect_status_info.setText("重连失败!");
					break;
					
				case 4:
					mNetErrorView.setVisibility(View.GONE);
					String udid = "";
					String partnerid = "";
					try{
						udid = mXmppFacade.getXmppConnectionAdapter().getAdaptee().UDID;
						partnerid = mXmppFacade.getXmppConnectionAdapter().getMService().getPartnerid();
					}catch(Exception e){
						e.printStackTrace();
					}
//					udidTextView.setText("udid="+udid);
//					partneridEditText.setText(partnerid);
//					getContactList();//20141025 added by allen
					break;
				case 5:
					mNetErrorView.setVisibility(View.VISIBLE);
					mConnect_status_info.setText("当前网络不可用，请检查你的网络设置。");
					break;
				case 6:
					if(mXmppFacade!=null 
//							&& mXmppFacade.getXmppConnectionAdapter()!=null 
//							&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null//&& !mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
//							&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected()
//							&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
							&& BeemConnectivity.isConnected(mContext)){
						
					}else{
						mNetErrorView.setVisibility(View.VISIBLE);
						if(BeemConnectivity.isConnected(mContext))
						mConnect_status_info.setText("网络可用,连接中...");
					}
					break;	
				}
			}

		};
		private BroadcastReceiver mNetWorkReceiver = new BroadcastReceiver() {
	        @Override
	        public void onReceive(Context context, Intent intent) {
	            String action = intent.getAction();  
	            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {  
	                Log.d("PoupWindowContactList", "网络状态已经改变");  
//	                connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);  
//	                info = connectivityManager.getActiveNetworkInfo();    
//	                if(info != null && info.isAvailable()) {  
//	                    String name = info.getTypeName();  
//	                    Log.d(tag, "当前网络名称：" + name);  
//	                    //doSomething()  
//	                } else {  
//	                    Log.d(tag, "没有可用网络");  
//	                  //doSomething()  
//	                }  
	                if(BeemConnectivity.isConnected(context)){
//	                	mNetErrorView.setVisibility(View.GONE);
//	                	isconnect = 0;
	                	mHandler3.sendEmptyMessage(6);//4
	                }else{
//	                	mNetErrorView.setVisibility(View.VISIBLE);
//	                	isconnect = 1;
	                	mHandler3.sendEmptyMessage(5);
	                	Log.d("PoupWindowContactList", "当前网络不可用，请检查你的网络设置。");
	                }
	            } 
	        }
		};
		
		private boolean phonestate = false;//false其他， true接起电话或电话进行时 
	    /* 内部class继承PhoneStateListener */
	    public class exPhoneCallListener extends PhoneStateListener
	    {
	        /* 重写onCallStateChanged
	        当状态改变时改变myTextView1的文字及颜色 */
	        public void onCallStateChanged(int state, String incomingNumber)
	        {
	          switch (state)
	          {
	            /* 无任何状态时 :说明没有拨打电话的界面的时候，也就是在拨打电话前和挂电话后的情况*/
	            case TelephonyManager.CALL_STATE_IDLE:
	            	Log.e("================20131216 无任何电话状态时================", "无任何电话状态时");
	            	if(phonestate){
	            		onPhoneStateResume();
	            	}
	            	phonestate = false;
	              break;
	            /* 接起电话时 :至少有一个电话存在、拨出或激活、接听，而没有一个电话在通话或等待的状态*/
	            case TelephonyManager.CALL_STATE_OFFHOOK:
	            	Log.e("================20131216 接起电话时================", "接起电话时");
	            	onPhoneStatePause();
	            	phonestate = true;
	              break;
	            /* 电话进来时 :在通话的过程中*/
	            case TelephonyManager.CALL_STATE_RINGING:
//	              getContactPeople(incomingNumber);
	            	Log.e("================20131216 电话进来时================", "电话进来时");
//	            	onBackPressed();
	            	onPhoneStatePause();
	            	phonestate = true;
	              break;
	            default:
	              break;
	          }
	          super.onCallStateChanged(state, incomingNumber);
	        }
	    }
	    
	    protected void onPhoneStatePause() {
//			super.onPause();
	    	try{
//	    		try {
//	    		    if (mRoster != null) {
//	    			mRoster.removeRosterListener(mBeemRosterListener);
//	    			mRoster = null;
//	    		    }
//	    		} catch (RemoteException e) {
//	    		    Log.d("ContactList", "Remote exception", e);
//	    		}
				if (mBinded) {
					getApplicationContext().unbindService(mServConn);
				    mBinded = false;
				}
				mXmppFacade = null;
	    	}catch(Exception e){
	    		e.printStackTrace();
	    	}
	    }
	    
	    protected void onPhoneStateResume() {
//			super.onResume();
	    	try{
			if (!mBinded){
//			    new Thread()
//			    {
//			        @Override
//			        public void run()
//			        {
			    mBinded = getApplicationContext().bindService(SERVICE_INTENT, mServConn, BIND_AUTO_CREATE);

//			        }
//			    }.start();		    
			}
			if (mBinded){
				mImageFetcher.setExitTasksEarly(false);
			}
	    	}catch(Exception e){
	    		e.printStackTrace();
	    	}
	    }
	    
	    /*
	     * 打开设置网络界面
	     * */
	    public static void setNetworkMethod(final Context context){
	        //提示对话框
	        AlertDialog.Builder builder=new AlertDialog.Builder(context);
	        builder.setTitle("网络设置提示").setMessage("网络连接不可用,是否进行设置?").setPositiveButton("设置", new DialogInterface.OnClickListener() {
	            
	            @Override
	            public void onClick(DialogInterface dialog, int which) {
	                // TODO Auto-generated method stub
	                Intent intent=null;
	                //判断手机系统的版本  即API大于10 就是3.0或以上版本 
	                if(android.os.Build.VERSION.SDK_INT>10){
	                    intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
	                }else{
	                    intent = new Intent();
	                    ComponentName component = new ComponentName("com.android.settings","com.android.settings.WirelessSettings");
	                    intent.setComponent(component);
	                    intent.setAction("android.intent.action.VIEW");
	                }
	                context.startActivity(intent);
	            }
	        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
	            
	            @Override
	            public void onClick(DialogInterface dialog, int which) {
	                // TODO Auto-generated method stub
	                dialog.dismiss();
	            }
	        }).show();
	    }
		//网络状态 end
}
